package com.liangtian.mdm.system.permission.service.impl;

import com.liangtian.mdm.base.exception.TransactionalException;
import com.liangtian.mdm.system.menu.model.Menu;
import com.liangtian.mdm.system.permission.dao.SysRoleDao;
import com.liangtian.mdm.system.permission.model.SysRole;
import com.liangtian.mdm.system.permission.model.SysRoleMenu;
import com.liangtian.mdm.system.permission.model.SysRoleUGroup;
import com.liangtian.mdm.system.permission.model.SysRoleUser;
import com.liangtian.mdm.system.permission.service.SysRoleService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.service.role.impl </p>
 * <p>Project Name: chccig-dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-04-28 11:50</p>
 * <p>Description :  角色持久层 </p>
 *
 * @author : hj
 * @version :  1.0
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    //注入角色持久层dao接口
    @Autowired
    SysRoleDao roleDao;

    /**
     * @param role 对象
     * @return 受影响的行数
     * @desc 新增角色
     */
    @Override
    public int insertRole(SysRole role, Long[] ids) throws TransactionalException {
        int result = 0;
        int count = roleDao.addRole(role);
        if (count > 0) {
            try {
                Map<String, Object> param = new HashMap<>();
                param.put("ids", ids);
                param.put("roleId", role.getRoleId());
                int num = roleDao.insertRolePermissionRef(param);
                if (num == ids.length) {
                    result = 1;
                } else {
                    throw new TransactionalException("新增角色与资源中间表错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        } else {
            throw new TransactionalException("新增角色事务异常");
        }
        return result;
    }

    /**
     * @param role 对象
     * @return 受影响的行数
     * @desc 编辑 （编辑数据；启用1；禁用-0）
     */
    @Override
    public int updateRole(SysRole role, Long[] ids) throws TransactionalException {
        int result = 0;
        int count = roleDao.editRole(role); //编辑用户
        if (count > 0) {
            try {
                Map<String, Object> deleteParams = new HashMap<>();
                deleteParams.put("roleId", role.getRoleId());
                int num = roleDao.deleteRolePermissionRef(deleteParams);//根据角色Id 删除中间表数据
                if (num > 0) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("ids", ids);
                    param.put("roleId", role.getRoleId());
                    int number = roleDao.insertRolePermissionRef(param);
                    if (number > 0) {
                        result = 1;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new TransactionalException("新增角色事务异常");
        }
        return result;
    }

    /**
     * @param params
     * @return 受影响的行数
     * @desc 批量删除角色数据
     * @params参数详情 roleId 角色编号
     */
    @Override
    public int batchDeleteRole(Map<String, Object> params) throws TransactionalException {
        int result = 0;
        int count = roleDao.batchDeleteRole(params);
        if (count > 0) {
            try {
                int num = roleDao.batchDeleteRolePermissionRef(params);
                if (num > 0) {
                    result = 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new TransactionalException("批量删除角色事务异常");
        }
        return result;
    }

    /**
     * @param role 分页数据的信息
     * @return 角色信息
     * @desc 获取全部的角色信息
     * @params参数详情 roleName 权限名称
     * @params参数详情 roleStatus 权限状态
     * @params参数详情 length 每页显示条数
     * @params参数详情 pageNum 页码
     * @params参数详情 start 起始条数
     * @params参数详情 draw 请求次数
     */
    @Override
    public PageInfo queryAllRole(SysRole role) {
        Integer pageNum = role.getPageNum();
        Integer length = role.getLength();
        PageHelper.startPage(pageNum, length);
        //获取文档数据
        List<Map<String, Object>> list = roleDao.queryAllRole(role);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @return 受影响的行数
     * @desc 编辑角色状态
     */
    @Override
    public SysRole queryDocumentByRole(SysRole role) {
        return roleDao.queryDocumentByRole(role);
    }

    /**
     * @param params
     * @return 受影响的行数
     * @desc 删除角色权限的关联表数据
     * @params参数详情 roleId 角色编号
     * @params参数详情 permissionId 权限编号
     */
    @Override
    public int deleteRolePermissionRef(Map<String, Object> params) {
        return roleDao.deleteRolePermissionRef(params);
    }

    /**
     * @param insertParams
     * @return 受影响的行数
     * @desc 插入角色权限中间表
     * @params参数详情 roleId 角色编号
     * @params参数详情 permissionId 权限编号
     */
    @Override
    public void insertRolePermissionRef(Map<String, Object> insertParams) {
        roleDao.insertRolePermissionRef(insertParams);
    }

    /**
     * @return 受影响的行数
     * @desc 编辑角色状态
     * @params参数详情 permissionId 权限编号
     */
    @Override
    public int editRoleStatus(Map<String, Object> params) {
        return roleDao.editRoleStatus(params);
    }

    /**
     * @param role 分页数据的信息
     * @return 角色信息
     * @desc 获取全部的角色信息
     * @params参数详情 roleStatus 角色状态
     */
    @Override
    public List<Map<String, Object>> queryAllRoleList(SysRole role) {
        return roleDao.queryAllRole(role);
    }

    @Override
    public int addRole(SysRole role) {
        return roleDao.addRole(role);
    }

    /**
     * @param role 对象
     * @return 受影响的行数
     * @desc 新增角色
     */
    @Override
    public int insterRole(SysRole role) {
        return roleDao.insertSelective(role);
    }

    /**
     * @param role 对象
     * @return 受影响的行数
     * @desc 编辑 （编辑数据；启用1；禁用0）
     */
    @Override
    public int editRole(SysRole role) {
        return roleDao.editRole(role);
    }

    public List<SysRoleMenu> getSelectNode(String roleId) {
        return roleDao.getSelectNode(roleId);
    }

    @Override
    public List<Map<String, Object>> queryAllDitconaryList(Map<String, Object> params) {
        return roleDao.queryAllDitconaryList(params);
    }

    public List<Menu> getAllmenuTree() {
        return roleDao.getAllmenuTree();
    }

    /**
     * @param params
     * @return 受影响的行数
     * @desc 批量删除角色资源数据
     * @params参数详情 roleId 角色编号
     */
    @Override
    public int batchDeleteRolePermissionRef(Map<String, Object> params) {
        return roleDao.batchDeleteRolePermissionRef(params);
    }


    public List<SysRoleMenu> getBindRoleIds(String roleId) {
        return roleDao.getBindRoleIds(roleId);
    }

    public boolean delBindResourcesInfo(String roleId) {
        try {
            roleDao.delBindResourcesInfo(roleId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }

    public boolean deleteRoleUserGroup(Map<String, Object> param) {
        boolean flag = false;
        try {
            roleDao.deleteRoleUserGroup(param);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean deleteRoleUser(Map<String, Object> map) {
        boolean flag = false;
        try {
            roleDao.deleteRoleUser(map);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean saveBindResourcesInfo(Map<String, Object> param) {
        boolean flag = false;
        String[] midarray = (String[]) param.get("midarray");
        String[] mtarray = (String[]) param.get("mtarray");
        String[] modelIdarray = (String[]) param.get("modelIdarray");
        String roleId = (String) param.get("roleId");
        List<SysRoleMenu> sysRoleMenuList = new ArrayList<SysRoleMenu>();
        for (int i = 0; i < midarray.length; i++) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(String.valueOf(midarray[i]));
            if (modelIdarray.length > 0) {
                if (modelIdarray[i].equals("undefined") || modelIdarray[i] == "undefined") {
                    sysRoleMenu.setModelId("");
                } else {
                    sysRoleMenu.setModelId(String.valueOf(modelIdarray[i]));
                }
            }
            if (mtarray.length > 0) {
                if (mtarray[i].equals("undefined") || mtarray[i] == "undefined") {
                    sysRoleMenu.setMenuType("");
                } else {
                    sysRoleMenu.setMenuType(String.valueOf(mtarray[i]));
                }
            }
            sysRoleMenuList.add(sysRoleMenu);
        }
        try {
            roleDao.saveBindResourcesInfo(sysRoleMenuList);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean insertRoleUserGroup(Map<String, Object> param) {
        boolean flag = false;
        String[] ids = (String[]) param.get("ids");
        String roleId = (String) param.get("roleId");
        List<SysRoleUGroup> ugList = new ArrayList<SysRoleUGroup>();
        for (int i = 0; i < ids.length; i++) {
            SysRoleUGroup sysRoleUGroup = new SysRoleUGroup();
            sysRoleUGroup.setRoleId(roleId);
            String str = ids[i];
            sysRoleUGroup.setuGroupId(str);
            ugList.add(sysRoleUGroup);
        }

        try {
            roleDao.insertRoleUserGroup(ugList);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean insertRoleUser(Map<String, Object> param) {
        boolean flag = false;
        String[] ids = (String[]) param.get("ids");
        String roleId = (String) param.get("roleId");
        List<SysRoleUser> userList = new ArrayList<SysRoleUser>();
        for (int i = 0; i < ids.length; i++) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setRoleId(roleId);
            String str = ids[i];
            sysRoleUser.setUserId(str);
            userList.add(sysRoleUser);
        }

        try {
            roleDao.insertRoleUser(userList);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public PageInfo queryNoSelUGList(Map<String, Object> param) {
        PageInfo<List<SysRoleUGroup>> pageInfo = null;
        try {
            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());// 模型定义页面要显示数据条数
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<SysRoleUGroup> sysRoleUGList = roleDao.queryNoSelUGList(param);
            pageInfo = new PageInfo(sysRoleUGList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    public PageInfo queryNoSelUserList(Map<String, Object> param) {
        PageInfo<List<SysUser>> pageInfo = null;
        try {
            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());// 模型定义页面要显示数据条数
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<SysUser> roleUserList = roleDao.queryNoSelUserList(param);
            pageInfo = new PageInfo(roleUserList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    public PageInfo queryUGRoleList(Map<String, Object> param) {
        PageInfo<List<SysRoleUGroup>> pageInfo = null;
        try {
            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());// 模型定义页面要显示数据条数
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<SysRoleUGroup> roleUGList = roleDao.queryUGRoleList(param);
            pageInfo = new PageInfo(roleUGList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    public PageInfo queryUsersRoleList(Map<String, Object> param) {
        PageInfo<List<SysUser>> pageInfo = null;
        try {
            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());// 模型定义页面要显示数据条数
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<SysUser> roleUserList = roleDao.queryUsersRoleList(param);
            pageInfo = new PageInfo(roleUserList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    public PageInfo queryAllRoleShowList(Map<String, Object> map) {
        PageInfo<List<SysRole>> pageInfo = null;
        try {
            Object pNo = map.get("pageNum");
            int pageNum, pageSize;
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt((map.get("limit").toString()));// 模型定义页面要显示数据条数
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<SysRole> roleList = roleDao.queryAllRoleShowList(map);
            pageInfo = new PageInfo(roleList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    public void deleteByIds(String idsStr) {
        roleDao.deleteByIds(idsStr);
    }

    public void inseterRole(SysRole role) {
        roleDao.inseterRole(role);
    }

    public void saveRoleEdit(SysRole role) {
        roleDao.saveRoleEdit(role);
    }

    @Override
    public List<SysRoleMenu> getSelectNodeByUserId(String roleId) {
        return roleDao.getSelectNodeByUserId(roleId);
    }

    @Override
    public List<SysRoleMenu> getSelectNodeByGroupId(String roleId) {
        return roleDao.getSelectNodeByGroupId(roleId);
    }

    @Override
    public List<SysRole> getRoleListByUserAccount(String userAccount) {
        return roleDao.getRoleListByUserAccount(userAccount);
    }
}